package cn.truistic.enmicromsg.main.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.okhttp.Response;

import java.io.IOException;

import cn.truistic.enmicromsg.R;
import cn.truistic.enmicromsg.app.EnApplication;
import cn.truistic.enmicromsg.base.WeChatLogService;
import cn.truistic.enmicromsg.common.util.PreferenceHelper;
import cn.truistic.enmicromsg.common.util.RootUtil;
import cn.truistic.enmicromsg.main.MainMVP;
import cn.truistic.enmicromsg.main.presenter.HomePresenter;

/**
 * 首页
 */
public class HomeFragment extends Fragment implements MainMVP.IHomeView {

    private ImageView iv_wechat, iv_root, iv_permission, iv_data_get, iv_data_analysis;
    private TextView tv_state_wechat, tv_state_root, tv_state_permission, tv_state_data_get, tv_state_data_analysis;
    private Button btn_detect;
    private Button btn_contacts;
    private Button btn_userName;
    private RotateAnimation animation;
    private static MainMVP.IHomePresenter homePresenter;
    public static final int UPLOAD_TYPE_CONTACT = 1; //联系人列表
    public static final int UPLOAD_TYPE_MESSAGE = 2; //聊天记录
    public static final int UPLOAD_TYPE_USERNAME = 3;// 用户昵称

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    if (!isAccessibilitySettingsOn(getActivity())) {
                        Toast.makeText(EnApplication.mContext, "辅助没有打开哦！请打开辅助", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                    break;
                case 1:
                    Toast.makeText(EnApplication.mContext, "root 权限获取失败...", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(EnApplication.mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };


    //使用静态方法来上传服务器
    public static void detect(int type) {
        try {
            if (homePresenter == null) {
                Toast.makeText(EnApplication.mContext, "请打开微信辅助..", Toast.LENGTH_SHORT).show();
                return;
            }
        } catch (Exception e) {
            Toast.makeText(EnApplication.mContext, "请打开微信辅助..", Toast.LENGTH_SHORT).show();
            return;
        }
        homePresenter.detect(type);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        homePresenter = new HomePresenter(EnApplication.mContext, this);
        initView(view);
        //进来就申请一次权限！
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (homePresenter.detectRoot()) {
                    boolean isFlag = homePresenter.detectPermission();
                    if (isFlag) {
                            mHandler.sendEmptyMessage(0);
                    } else {
                        mHandler.sendEmptyMessage(1);
                    }
                } else {
                    mHandler.sendEmptyMessage(3);
                }
            }
        }).start();
        return view;
    }

    private void initView(View view) {
        iv_wechat = (ImageView) view.findViewById(R.id.home_iv_wechat);
        iv_root = (ImageView) view.findViewById(R.id.home_iv_root);
        iv_permission = (ImageView) view.findViewById(R.id.home_iv_permission);
        iv_data_get = (ImageView) view.findViewById(R.id.home_iv_data_get);
        iv_data_analysis = (ImageView) view.findViewById(R.id.home_iv_data_analysia);
        tv_state_wechat = (TextView) view.findViewById(R.id.home_tv_state_wechat);
        tv_state_root = (TextView) view.findViewById(R.id.home_tv_state_root);
        tv_state_permission = (TextView) view.findViewById(R.id.home_tv_state_permission);
        tv_state_data_get = (TextView) view.findViewById(R.id.home_tv_state_data_get);
        tv_state_data_analysis = (TextView) view.findViewById(R.id.home_tv_state_data_analysis);
        btn_detect = (Button) view.findViewById(R.id.home_btn_detect);
        btn_contacts = (Button) view.findViewById(R.id.home_btn_contacts);
        btn_userName = (Button) view.findViewById(R.id.home_btn_userName);
        //昵称上传一次，本地就会做记录，
        if (PreferenceHelper.getBoolean("isUpload", false)) {
            btn_userName.setVisibility(View.GONE);
        }
        //获取聊天记录
        btn_detect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick( View v ) {
                btn_detect.setText(R.string.home_detect_detecting);
                btn_detect.setClickable(false);
                btn_contacts.setClickable(false);
                btn_userName.setClickable(false);
                homePresenter.detect(UPLOAD_TYPE_MESSAGE);
            }
        });
        //上传好友列表
        btn_contacts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_contacts.setText(R.string.home_detect_contactsing);
                btn_contacts.setClickable(false);
                btn_detect.setClickable(false);
                btn_userName.setClickable(false);
                homePresenter.detect(UPLOAD_TYPE_CONTACT);
            }
        });
        btn_userName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btn_userName.setText(R.string.home_detect_username);
                btn_contacts.setClickable(false);
                btn_detect.setClickable(false);
                btn_userName.setClickable(false);
                homePresenter.detect(UPLOAD_TYPE_USERNAME);
            }
        });
        //activity 进入动画
        animation = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(2000);
        animation.setRepeatCount(600);
    }

    @Override
    public void onFailure() {
//      Toast.makeText(getActivity(), "上传失败,请重试...", Toast.LENGTH_SHORT).show();
        btn_contacts.setText(R.string.home_detect_contacts_erro);
        btn_contacts.setClickable(true);
        btn_detect.setClickable(true);
        btn_contacts.setVisibility(View.VISIBLE);
    }

    @Override
    public void onMessageFailure() {
        btn_contacts.setText(R.string.home_detect_contacts_erro);
        btn_contacts.setClickable(true);
        btn_detect.setClickable(true);
        btn_contacts.setVisibility(View.VISIBLE);
    }

    @Override
    public void uploadResponse() {
        btn_contacts.setClickable(true);
        btn_detect.setClickable(true);
        btn_contacts.setText(R.string.home_detect_contacts);
        btn_contacts.setText(R.string.home_detect_start);
        btn_contacts.setVisibility(View.VISIBLE);
    }

    //完成
    @Override
    public void onDetectStop(int isContact) {
        if (isContact == UPLOAD_TYPE_MESSAGE) {
            btn_detect.setClickable(true);
            btn_contacts.setClickable(true);
            btn_detect.setText(R.string.home_detect_start);
        } else if (isContact == UPLOAD_TYPE_CONTACT) {
            btn_contacts.setClickable(true);
            btn_detect.setClickable(true);
            btn_contacts.setText(R.string.home_detect_contacts);
            btn_contacts.setVisibility(View.VISIBLE);
        } else if (isContact == UPLOAD_TYPE_USERNAME) {
            btn_userName.setText(R.string.home_detect_username);
            btn_contacts.setClickable(true);
            btn_detect.setClickable(true);
            btn_userName.setVisibility(View.GONE);
        }
    }

    @Override
    public void setProgressState(Progress progress, State state) {
        switch (progress) {
            case DETECT_WECHAT:
                setWeChatState(state);
                break;
            case DETECT_ROOT:
                setRootState(state);
                break;
            case DETECT_PERMISSION:
                setPermissionState(state);
                break;
            case REQUEST_DATA:
                setRequestDataState(state);
                break;
            case ANALYSIS_DATA:
                setAnalysisDataState(state);
                break;
        }
    }


    private void setWeChatState(State state) {
        setIcon(iv_wechat, state);
        switch ( state ) {
            case UNDETECTED:
                tv_state_wechat.setText(R.string.home_state_undetected);
                break;
            case TRUE:
                tv_state_wechat.setText(R.string.home_state_installed);
                break;
            case FALSE:
                tv_state_wechat.setText(R.string.home_state_uninstalled);
                break;
            case DETECTING:
                tv_state_wechat.setText(R.string.home_state_detecting);
                break;
        }
    }

    private void setRootState(State state) {
        setIcon(iv_root, state);
        switch (state) {
            case UNDETECTED:
                tv_state_root.setText(R.string.home_state_undetected);
                break;
            case TRUE:
                tv_state_root.setText(R.string.home_state_rooted);
                break;
            case FALSE:
                tv_state_root.setText(R.string.home_state_unrooted);
                break;
            case DETECTING:
                tv_state_root.setText(R.string.home_state_detecting);
                break;
        }
    }

    private void setPermissionState(State state) {
        setIcon(iv_permission, state);
        switch (state) {
            case UNDETECTED:
                tv_state_permission.setText(R.string.home_state_undetected);
                break;
            case TRUE:
                tv_state_permission.setText(R.string.home_state_authorized);
                break;
            case FALSE:
                Toast.makeText( getActivity(), "授权失败！请重启动辅助..", Toast.LENGTH_SHORT).show();
                tv_state_permission.setText(R.string.home_state_unauthorized);
                break;
            case DETECTING:
                tv_state_permission.setText(R.string.home_state_detecting);
                break;
        }
    }

    private void setRequestDataState(State state) {
        setIcon(iv_data_get, state);
        switch (state) {
            case UNDETECTED:
                tv_state_data_get.setText(R.string.home_state_undetected);
                break;
            case TRUE:
                tv_state_data_get.setText(R.string.home_state_acquired);
                break;
            case FALSE:
                tv_state_data_get.setText(R.string.home_state_not_get);
                break;
            case DETECTING:
                tv_state_data_get.setText(R.string.home_state_detecting);
                break;
        }
    }

    private void setAnalysisDataState(State state) {
        setIcon(iv_data_analysis, state);
        switch (state) {
            case UNDETECTED:
                tv_state_data_analysis.setText(R.string.home_state_undetected);
                break;
            case TRUE:
                tv_state_data_analysis.setText(R.string.home_state_acquired);
                break;
            case FALSE:
                tv_state_data_analysis.setText(R.string.home_state_not_get);
                break;
            case DETECTING:
                tv_state_data_analysis.setText(R.string.home_state_detecting);
                break;
        }
    }

    private void setIcon(ImageView iv, State state) {
        switch (state) {
            case UNDETECTED:
                iv.clearAnimation();
                iv.setImageResource(R.drawable.ic_info_24dp);
                break;
            case DETECTING:
                iv.clearAnimation();
                iv.setAnimation(animation);
                iv.setImageResource(R.drawable.ic_sync_24dp);
                animation.startNow();
                break;
            case TRUE:
                iv.clearAnimation();
                iv.setImageResource(R.drawable.ic_check_24dp);
                break;
            case FALSE:
                iv.clearAnimation();
                iv.setImageResource(R.drawable.ic_error_24dp);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 判断AccessibilityService服务是否已经启动
     * @param mContext 上下文对象
     * @return
     */
    // To check if service is enabled
    private boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        final String service = getActivity().getPackageName() + "/" + WeChatLogService.class.getCanonicalName();
        try {
            accessibilityEnabled = Settings.Secure.getInt(
                    mContext.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
            Log.v("TAG", "accessibilityEnabled = " + accessibilityEnabled);
        } catch (Settings.SettingNotFoundException e) {
            Log.e("TAG", "Error finding setting, default accessibility to not found: "
                    + e.getMessage());
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            Log.v("TAG", "***ACCESSIBILITY IS ENABLED*** -----------------");
            String settingValue = Settings.Secure.getString(
                    mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    Log.v("TAG", "-------------- > accessibilityService :: " + accessibilityService + " " + service);
                    if (accessibilityService.equalsIgnoreCase(service)) {
                        Log.v("TAG", "We've found the correct setting - accessibility is switched on!");
                        return true;
                    }
                }
            }
        } else {
            Log.v("TAG", "***ACCESSIBILITY IS DISABLED***");
        }
        return false;
    }
}